package com.qingxin.sys.verifier.rules;

import java.util.HashMap;
import java.util.Map;

import com.qingxin.sys.verifier.FormMap;
import com.qingxin.sys.verifier.VerifyRule;

/**
 * 用于判断一组表单项中必须有不少于指定项的不为空
 * @author Administrator
 *
 */
public class AnyItemRule extends VerifyRule {

	private String destid;
	private String destname;
	private int min;
	
	
	public AnyItemRule() {
		this.destid = "";
		this.destname = "";
		this.min = 1;
	}

	
	@Override
	public boolean isValid(String name, String label, FormMap formMap) {
		int num = 0;
		boolean thispass = false;
		String value = formMap.getParameter(name);
		if(!isEmpty(value) && value.matches("^[\\s\\S]*[^\\s\u3000]+[\\s\\S]*$")){
			num++;
			thispass = true;
		}
		if(!isEmpty(destname)){
			String[] dest = destname.split("[,;]");
			for(String dname : dest){
				value = formMap.getParameter(dname);
				if(!isEmpty(value) && value.matches("^[\\s\\S]*[^\\s\u3000]+[\\s\\S]*$")){
					num++;
				}
			}
		}
		if(num >= min || thispass){
			return true;
		}
		message = createMessage(null, "{name}", label, "{label}", label);
		if(isEmpty(message)){
			message = "不能为空.";
		}
		return false;
	}

	
	@Override
	public Map<String, Object> getRuleCfg(String name, String label) {
		if(isEmpty(getDestid())){
			return null;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("rtype", "anyitem");
		String destid = getDestid();
		if(isEmpty(destid)){
			map.put("dest", new String[0]);
		}else{
			map.put("dest", getDestid().split("[,;]"));
		}
		map.put("min", min);
		
		String errormsg = createMessage(null, "{name}", label, "{label}", label);
		if(!isEmpty(errormsg)){
			map.put("error", errormsg);
		}else {
			map.put("error", "不能为空.");
		}
		
		return map;
	}

	
	public String getDestid() {
		if(isEmpty(destid)){
			return destname;
		}
		return destid;
	}
	public void setDestid(String destid) {
		this.destid = destid;
	}
	public String getDestname() {
		return destname;
	}
	public void setDestname(String destname) {
		this.destname = destname;
	}
	public int getMin() {
		return min;
	}
	public void setMin(int min) {
		this.min = min;
	}
	
}
